import {createGlobalState, useStorage} from "@vueuse/core";
import mxConst from "../common/mxConst.js";
import {genMixColor} from "../utils/gen-color.ts";

export const useTheme = createGlobalState(() => {
    // data
    const defaultTheme = {
        // brands 里的颜色会自动生成多种变种，如 lighter、light、DEFAULT、deep、deeper
        brands: {
            primary: '#d50000',
            success: '#6ad000',
            warning: '#ff9800',
            error: '#f44336',
            info: '#999999'
        },
        // colors 里的颜色仅会生成 DEFAULT
        colors: {
            main: '#303133',
            content: '#606266',
            tips: '#909193',
            light: '#c0c4cc',
            border: '#dadbde',
            bg: '#f5f4f3',
            disabled: '#c8c9cc'
        }
    }
    const theme = useStorage(mxConst.keyTheme, defaultTheme)

    // methods
    const setTheme = (newTheme = {}) => {
        const mergedTheme = uni.$uv.deepMerge(defaultTheme, newTheme)
        theme.value = mergedTheme
        updateThemeColorVar(mergedTheme)
    }

    const setStyleProperty = (propName, value) => {
        document.documentElement.style.setProperty(propName, value);
    }

    const updateBrandExtendColorsVar = (color, name) => {
        // 生成混合色
        const {
            DEFAULT,
            dark,
            light
        } = genMixColor(color);
        // 每种主题色由浅到深分为五个阶梯以供开发者使用。
        setStyleProperty(`--${name}-lighter-color`, light[5]);
        setStyleProperty(`--${name}-light-color`, light[3]);
        setStyleProperty(`--${name}-color`, DEFAULT);
        setStyleProperty(`--${name}-deep-color`, dark[2]);
        setStyleProperty(`--${name}-deeper-color`, dark[4]);

        // elementPlus主题色更新
        setStyleProperty(`--el-color-${name}`, DEFAULT);
        setStyleProperty(`--el-color-${name}-dark-2`, dark[2]);
        setStyleProperty(`--el-color-${name}-light-3`, light[3]);
        setStyleProperty(`--el-color-${name}-light-5`, light[5]);
        setStyleProperty(`--el-color-${name}-light-7`, light[7]);
        setStyleProperty(`--el-color-${name}-light-8`, light[8]);
        setStyleProperty(`--el-color-${name}-light-9`, light[9]);
    }

    const updateThemeColorVar = ({brands, colors}) => {
        // 遍历当前主题色，生成混合色，并更新到css变量（tailwind + elementPlus）
        for (const [name, color] of Object.entries(colors)) {
            setStyleProperty(`--${name}-color`, color);
        }
        for (const [brand, color] of Object.entries(brands)) {
            updateBrandExtendColorsVar(color, brand)
        }
    }


    return {
        theme,
        setTheme
    }
})
